package main

import (
	"fmt"
	"log"
	"net/http"

	"github.com/xuri/excelize/v2"
)

// go操作excel

func down(w http.ResponseWriter, r *http.Request) {
	f := excelize.NewFile()
	// Set value of a cell.
	f.SetCellValue("Sheet1", "A2", "Hello World")
	// Save xlsx file by the given path.
	//if err := f.SaveAs("Book.xlsx"); err != nil {
	//    fmt.Println(err)
	//}

	w.Header().Set("Content-Type", "application/octet-stream")
	w.Header().Set("Content-Disposition", "attachment; filename="+"Book.xlsx")
	w.Header().Set("Content-Transfer-Encoding", "binary")
	_ = f.Write(w)
}

func main() {
	// 1. 创建excel文件
	// f := excelize.NewFile()
	// // Create a new sheet.
	// index, _ := f.NewSheet("Sheet2")
	// // Set value of a cell.
	// f.SetCellValue("Sheet2", "A2", "Hello world.")
	// //设置单元格样式
	// style, err := f.NewStyle(`{"font":{"bold": true,"family": "font-family","size": 20,"color": "#777777"}}`)
	// if err != nil {
	// 	fmt.Println(err)
	// }
	// f.SetCellStyle("Sheet1", "B1", "B1", style)
	// f.SetCellValue("Sheet1", "B1", "hello")

	// // Set active sheet of the workbook.
	// f.SetActiveSheet(index)
	// // Save xlsx file by the given path.
	// if err := f.SaveAs("Book.xlsx"); err != nil {
	// 	fmt.Println(err)
	// }

	// 2. 读取excel文件
	fw, err := excelize.OpenFile("Book.xlsx")
	if err != nil {
		fmt.Println(err)
		return
	}
	// Get value from cell by given worksheet name and axis.
	cell, err := fw.GetCellValue("Sheet1", "B2")
	if err != nil {
		fmt.Println(err)
		return
	}
	fmt.Println(cell)
	// Get all the rows in the Sheet1.
	rows, err := fw.GetRows("Sheet1")
	for _, row := range rows {
		for _, colCell := range row {
			fmt.Print(colCell, "\t")
		}
		fmt.Println()
	}

	// 3. 生成excel文件并下载
	http.HandleFunc("/", down)
	// 设置访问路由
	log.Fatal(http.ListenAndServe(":8080", nil))
}
